package com.woniu.exceptions;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.woniu.entity.ResponseEntity;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.security.auth.login.LoginException;

/**
 * @Author: Wenxin
 * @Todo:
 * @DateTime: 22/09/06/0006 16:21
 * @Component:
 **/
@RestControllerAdvice
public class GlobalExceptionControllerAdvice {
    /**
     * shiro相关的异常：网上还有很多其他异常处理方案
     * ChangeLog : 1. 创建 (22/09/06/0006 16:26 [马宇航]);
     *
     * @param e
     * @return com.woniuxy.entity.ResponseEntity
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public ResponseEntity handler401(ShiroException e) {
        e.printStackTrace();
        return new ResponseEntity(HttpStatus.UNAUTHORIZED.value(), e.getMessage(), null);
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthenticatedException.class)
    public ResponseEntity handlerUnauthorizedException(UnauthenticatedException e) {
        e.printStackTrace();
        return new ResponseEntity(HttpStatus.UNAUTHORIZED.value(), e.getMessage(), null);
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity handlerUnauthorizedException(AuthenticationException e) {
        e.printStackTrace();
        return new ResponseEntity(HttpStatus.UNAUTHORIZED.value(), e.getMessage(), null);
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(JWTVerificationException.class)
    public ResponseEntity handlerUnauthorizedException(JWTVerificationException e) {
        e.printStackTrace();
        return new ResponseEntity(HttpStatus.FORBIDDEN.value(), e.getMessage(), null);
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ResponseEntity globalException(Throwable e) {
        e.printStackTrace();
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), null);
    }

    //登陆失败的异常
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(LoginException.class)
    public ResponseEntity loginException(Throwable e) {
        e.printStackTrace();
        return new ResponseEntity(HttpStatus.FORBIDDEN.value(), e.getMessage(), null);
    }
}
